import 'package:fish_redux/fish_redux.dart';
import 'action.dart';
import 'state.dart';
import '../../../../app_files.dart';

Effect<FixWorkerListViewState> buildEffect() {
  return combineEffects(<Object, Effect<FixWorkerListViewState>>{
    FixWorkerListViewAction.onLoad: _onLoad,
    FixWorkerListViewAction.onTapIndex: _onTapIndex,
    Lifecycle.initState: _initState,
  });
}

void _onTapIndex(Action action, Context<FixWorkerListViewState> ctx) async {
  FixWorkerModel model = action.payload;
  if (model.userID == GlobalStore.store.getState().userInfo.userid) {
    CommonUtils.showErrorInfo(ctx.context, '接单人员不能选择自己');
    return;
  }
  if (ctx.state.currentWorker != null &&
      model.userID == ctx.state.currentWorker.userID)
    ctx.state.currentWorker = null;
  else
    ctx.state.currentWorker = action.payload;
  ctx.dispatch(FixWorkerListViewActionCreator.onAction());
}

void _initState(Action action, Context<FixWorkerListViewState> ctx) async {
  await _sendRequest(ctx);
}

void _onLoad(Action action, Context<FixWorkerListViewState> ctx) async {
  await _sendRequest(ctx);
}

_sendRequest(Context<FixWorkerListViewState> ctx) async {
  ResultData res = await CommonNetWork.staffFixWorkerList();
  if (res.success) {
    List data = res.data['data'];
    ctx.state.workers =
        data.map<FixWorkerModel>((e) => FixWorkerModel.fromJson(e)).toList();

    ctx.state.refreshController.finishRefresh();
    ctx.dispatch(FixWorkerListViewActionCreator.onAction());
  } else {
    await CommonUtils.showAlertView(ctx.context, res.desc);
    Navigator.pop(ctx.context);
    return;
  }
}
